#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



##TBD
import json

from flask import Blueprint
from flask import current_app as app
from marshmallow import INCLUDE
from webargs import fields
from webargs.flaskparser import use_args

from config.config import read_client_config
from config.config import read_server_version
from extensions.exception import FceException
from common_libs.helper import response_data

update_controller = Blueprint('update', __name__, url_prefix='/update')

# get config
@update_controller.route('/getClientConfig', methods=['POST'])
@use_args({
    "RequestId": fields.Str(required=True)
}, location="form", unknown=INCLUDE)
def getClientConfig(args):
    request_id = args.get('RequestId')
    app.logger.info('RequestId:%s getClientConfig', request_id)
    try:
        config = read_client_config()
    except Exception as e:
        FceException('OperationFailed.SystemCommand', 'read json config')
    
    data = {
        "RequestId": request_id,
        "Config":json.dumps(config)
    }
    return response_data(True, data, "Success")

# get serverversion
@update_controller.route('/getServerVersion', methods=['POST'])
@use_args({
    "RequestId": fields.Str(required=True)
}, location="form", unknown=INCLUDE)
def getServerVersion(args):
    request_id = args.get('RequestId')
    app.logger.info('RequestId:%s getServerVersion', request_id)
    
    try:
        version_info = read_server_version().split('\n')[0]
        version = version_info.split('(')[0]
    except Exception as e:
        FceException('OperationFailed.SystemCommand', 'read server version')
    
    data = {
        "RequestId": request_id,
        "Version":version,
        "VersionInfo":version_info
    }
    return response_data(True, data, "Success")


# get checkCompatibility
@update_controller.route('/checkCompatibility', methods=['POST'])
@use_args({
    "RequestId": fields.Str(required=True),
    "ClientVersion": fields.Str(required=True),
    "ServerVersion": fields.Str(required=False),
}, location="form", unknown=INCLUDE)
def checkCompatibility(args):
    request_id = args.get('RequestId')
    client_version = args.get('ClientVersion')

    if 'ServerVersion' in args:
        server_version = args.get('ServerVersion')
    else:
        try:
            version_info = read_server_version().split('\n')[0]
            server_version = version_info.split('(')[0]
        except Exception as e:
            FceException('OperationFailed.SystemCommand', 'read server version')



    app.logger.info('RequestId:%s checkCompatibility %s args', request_id,args)

    client_version_first = client_version.split('.')[0]
    client_version_second = client_version.split('.')[1]+client_version.split('.')[2]

    server_version_first = server_version.split('.')[0]
    server_version_second = server_version.split('.')[1]+server_version.split('.')[2]

    if server_version_first == client_version_first and server_version_second >= client_version_second:
        IsCompatible = 'true'
    else:
        IsCompatible = 'false'
    
    avail_version_old = ["v2021.5.7.1.0","v2021.5.7.1.1","v2021.5.7.1.2","v2021.5.7.1.3","v2021.5.7.1.4"]
    avail_version_new = []

    for i in avail_version_old:
        version = i.split('.')[1]+i.split('.')[2]
        if version <= server_version_second:
            avail_version_new.append(i)

    app.logger.info(avail_version_new)

    data = {
        "RequestId": request_id,
        "IsCompatible": IsCompatible,
        "AvailVersion": avail_version_new
    }
    return response_data(True, data, "Success")